package com.example.anday3;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewStub;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.example.anday3.pojo.LoginResData;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class LoginActivity extends AppCompatActivity implements View

        .OnClickListener {
    Button button;
    EditText userEditText;
    EditText passEditText;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_login);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
        button=findViewById(R.id.loginbtn);
        userEditText=findViewById(R.id.username);
        passEditText=findViewById(R.id.password);
        button.setOnClickListener(this);

    }

    @Override
    public void onClick(View view) {
        OkHttpClient http=new OkHttpClient();
        RequestBody body=new FormBody.Builder().
                add("loginname",userEditText.getText().toString())
                .add("password",passEditText.getText().toString())
                .build();
        Request request=new Request.Builder().url("http://123.56.141.187:4001/user/login").post(body).build();
        http.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.d("error",e.toString());
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                String str=response.body().string();
                Log.d("sls",str);
             LoginResData loginResData=LoginResData.objectFromData(str);
                if(loginResData.getState()==200){
                    runOnUiThread(()->{
                        startActivity(new Intent(LoginActivity.this,MainActivity.class));
                    });

                }
                else{
                    Log.d("error","登录失败");
                }
            }
        });

    }
}